package com.huawei.codearts.controller;

import com.huawei.codearts.service.OrderService;
import com.huawei.codearts.service.RedisService;
import com.huawei.codearts.tools.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping(value = "/redis")
public class RedisController {

    @Autowired
    private RedisService redisService;

    @RequestMapping(value = "/get")
    public String get(@RequestParam Map<String, Object> params) {
        // @RequestBody 接收json参数
        // @RequestParam 接收get或post参数, 如果get和post同时有参数并且参数名称相同, 则get参数会覆盖post参数
        System.out.println(params);
        System.out.println(params.get("id"));
        System.out.println(params.get("name"));

        // ResultExceptionAspect 添加了 @Around 集成了异常和日志处理
        // 因此这里不需要 try-catch
        // 以下所有方法里都可以去掉 try-catch
//        int i= 1 / 0;
        return ResponseUtils.response(redisService.getAndSet());
    }

    @RequestMapping(value = "/lock")
    public String lock(@RequestParam Map<String, Object> params) {
        String result = null;
        try {
            result = ResponseUtils.response(redisService.lock());
        } catch(Exception e) {
            result = ResponseUtils.logException(e);
        }
        return result;
    }

    // 延迟队列
    @RequestMapping(value = "/zadd")
    public String zadd(@RequestParam Map<String, Object> params) throws IOException {
        String result = ResponseUtils.error("zadd fail");
        long success = redisService.zadd();
        if (success > 0L) {
            result = ResponseUtils.ok();
        }
        return result;
    }

    // 队列
    @RequestMapping(value = "/push")
    public String push(@RequestParam Map<String, Object> params) {
        String result = ResponseUtils.error("push fail");
        try {
            long success = redisService.push();
            if (success > 0L) {
                result = ResponseUtils.ok();
            }
        } catch(Exception e) {
            result = ResponseUtils.logException(e);
        }
        return result;
    }

    @RequestMapping(value = "/queue")
    public String queue(@RequestParam Map<String, Object> params) {
        String result = null;
        try {
            result = ResponseUtils.response(redisService.queue());
        } catch(Exception e) {
            result = ResponseUtils.logException(e);
        }
        return result;
    }

}
